<template>
  <el-dialog :visible="modalVisible" :title="formData ? '编辑部门' : '新增部门'" @close="hide">
    <div style="width: 50%; margin-left: 5%">
      <el-form ref="orgEditRef" :model="form_data" label-width="100px" :rules="rules">
        <el-form-item v-show="false" prop="id">
          <el-input v-model="form_data.id"/>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form_data.name"/>
        </el-form-item>
        <el-form-item label="唯一编码" prop="code">
          <el-input v-model="form_data.code" :disabled="formData"/>
        </el-form-item>
        <el-form-item label="上级部门" prop="pid">
          <el-select v-model="form_data.pid" placeholder="">
            <el-option :value="currentOrg.id" :label="currentOrg.title" style="height: auto">
              <el-tree
                ref="orgTreeRef"
                default-expand-all
                :expand-on-click-node="false"
                :data="orgTreeData"
                node-key="id"
                highlight-current
                :props="{children: 'children', label: 'title', disabled: disabledNode}"
                @node-click="handleCheckChange"
              />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form_data.sort"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form_data.remark"/>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="modalVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { GetDepTree, SetOrg } from '@/api/system';

export default {
  name: 'EditDepartment',
  props: {
    formData: {
      type: Object,
      default: null
    }
  },
  data() {
    const validatePid = (rule, value, callback) => {
      if (this.form_data.pid !== '' && this.form_data.pid !== undefined) {
        callback()
      } else {
        callback(new Error('上级部门不能为空'));
      }
    };
    return {
      modalVisible: false,
      form_data: {
        sort: 100
      },
      orgTreeData: [],
      currentOrg: {},
      rules: {
        name: [
          {
            required: true, message: '部门名称不能为空', trigger: 'blur'
          }
        ],
        code: [
          {
            required: true, message: '唯一编码不能为空', trigger: 'blur'
          }
        ],
        pid: [
          {
            required: true, validator: validatePid
          }
        ]
      }
    }
  },
  watch: {
    formData: {
      immediate: true,
      deep: true,
      handler(n, o) {
        if (n && n !== o) {
          this.form_data = JSON.parse(JSON.stringify(n));
        } else {
          this.form_data = {
            sort: 100
          };
        }
      }
    }
  },
  methods: {

    disabledNode(data, node) {
      return data.disabled;
    },
    handleSubmit() {
      this.$refs['orgEditRef'].validate((res) => {
        if (res) {
          const requestBody = {
            ...this.form_data
          };
          SetOrg(requestBody).then(res => {
            if (res.code === 200) {
              this.$message.success(this.formData ? '编辑成功' : '新增成功');
              this.$emit('callback');
              this.hide();
            }
          });
        }
      });
    },
    handleCheckChange(data) {
      if (!data.disabled || !this.formData) {
        this.currentOrg = data;
        this.form_data.pid = data.id;
        // this.$refs['orgEditRef'].clearValidate();
        this.$refs['orgEditRef'].validateField('pid');
      } else {
        this.$message.warning('上级部门不可为自身');
      }
    },
    recursionGet(data, valueId) {
      let value = null;
      for (let index = 0; index < data.length; index += 1) {
        if (data[index].id === valueId) {
          value = data[index];
          break;
        }
        if (data[index].children instanceof Array && data[index].children.length > 0) {
          const text = this.recursionGet(data[index].children, valueId);
          if (text) {
            return text;
          }
        }
      }
      return value;
    },
    show() {
      this.modalVisible = true;
      this.getOrgTree();
    },
    hide() {
      this.form_data = {
        sort: 100
      };
      this.currentOrg = {};
      this.$refs['orgEditRef'].resetFields();
      this.modalVisible = false;
      this.$emit('callback');
    },
    mapTree(data) {
      data.forEach(items => {
        if (items.id === this.formData.id) {
          items.disabled = true
        } else {
          items.disabled = false
        }
        if (items.children) {
          this.mapTree(items.children)
        }
      });
    },
    getOrgTree() {
      GetDepTree().then(res => {
        if (res.code === 200) {
          if (this.formData) {
            this.mapTree(res.data);
          }
          this.orgTreeData = [{
            id: 0,
            title: '淮南统战部',
            children: res.data,
            disabled: false
          }];
          if (this.form_data.pid !== '' && this.form_data.pid !== undefined && this.form_data.pid !== null) {
            this.currentOrg = this.recursionGet(this.orgTreeData, this.form_data.pid)
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
